package com.southwind.controller;

import com.southwind.feign.MyFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    private DiscoveryClient discoveryClient;

//    @Autowired
//    private RestTemplate restTemplate;  // 需要手动配置

    @Autowired
    private MyFeignClient myFeignClient;

    /**
     * 服务发现
     */
    @GetMapping("list")
    public List<ServiceInstance> list() {
        // 发现nacos中注册的服务
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        return list;
    }

    /**
     * 服务调用
     */
    @GetMapping("index")
    public String index() {
//        // 发现nacos中注册的服务
//        List<ServiceInstance> list = discoveryClient.getInstances("provider");
//        // 用随机数模拟负载均衡
//        int i = ThreadLocalRandom.current().nextInt(list.size());
//        ServiceInstance serviceInstance = list.get(i);
//        String url = serviceInstance.getUri() + "/index";
//        // 远程调用
//        String result = restTemplate.getForObject(url, String.class);
//        return "consumer调用provider成功，返回值：" + result;


//        // 使用ribbon的负载均衡
//        String result = restTemplate.getForObject("http://provider/index", String.class);
//        return "【ribbon负载均衡】consumer调用provider成功，返回值：" + result;


        // 使用feign声明式接口调用
        String result = myFeignClient.index();
        return "【feign声明式接口调用】consumer调用provider成功，返回值：" + result;
    }
}
